package com.thd.springboottest.security.config;

import com.thd.springboottest.security.securitycustom.ThirdFilter;
import com.thd.springboottest.security.securitycustom.ThirdProvider;
import com.thd.springboottest.security.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.SecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * com.thd.springboottest.security.config.MobileSecurityConfig
 *
 * @author: wanglei62
 * @DATE: 2022/6/22 16:38
 **/
@Configuration
public class SecurityThirdConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain,HttpSecurity> {

    // 自定义登录成功处理器
    @Autowired
    private AuthenticationSuccessHandler myAuthenticationSuccessHandler;

    // 自定义登录失败处理器
    @Autowired
    private AuthenticationFailureHandler myAuthenticationFailureHandler;
    @Autowired
    private UserService userService;

    @Override
    public void configure(HttpSecurity http) throws Exception {

        ThirdFilter mobileFilter = new ThirdFilter();
        // 设置AuthenticationManager
        mobileFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        // 设置登录成功的处理器
        mobileFilter.setAuthenticationSuccessHandler(myAuthenticationSuccessHandler);
        // 设置登录失败的处理器
        mobileFilter.setAuthenticationFailureHandler(myAuthenticationFailureHandler);

        // 创建provider - 根据token获取登录人信息
        ThirdProvider thirdProvider = new ThirdProvider(userService);

        http.authenticationProvider(thirdProvider)
                .addFilterAfter(mobileFilter, UsernamePasswordAuthenticationFilter.class);
    }
}
